<template>
  <div>
    <a-space direction="vertical" fill size="medium">
      <a-card title="广告管理">
        <a-space size="large">
          广告是否展示 <a-switch v-model="adShow" @change="onAdShow"></a-switch>
        </a-space>
      </a-card>
      <a-card title="回传控制次数">
        <a-space size="large">
          <a-space size="large">
            广告控制回传次数
            <a-input-number v-model="initData.adShowCount"></a-input-number>
          </a-space>

          <a-button type="primary" @click="onSumbitInit">提交</a-button>
        </a-space>
      </a-card>
      <a-card title="广告初始展示项">
        <a-space size="large">
          <a-space size="large">
            <!-- 多选项 -->
            <a-checkbox-group
              v-model="adControl.initial"
              style="display: flex; gap: 12px"
            >
              <a-checkbox value="banner">banner</a-checkbox>
              <a-checkbox value="interstitial">interstitial</a-checkbox>
              <a-checkbox value="video">video</a-checkbox>
            </a-checkbox-group>
          </a-space>

          <a-button type="primary" @click="onSubmitAdInitial">提交</a-button>
        </a-space>
      </a-card>
      <a-card title="广告重复展示项">
        <!-- 选项 repeat -->

        <a-space
          size="large"
          style="display: flex; align-items: center; gap: 12px"
        >
          <div style="display: flex; gap: 12px; align-items: center">
            广告重复展示项
            <a-checkbox-group
              v-model="adControl.repeat"
              style="display: flex; gap: 12px"
            >
              <a-checkbox value="banner">banner</a-checkbox>
              <a-checkbox value="interstitial">interstitial</a-checkbox>
              <a-checkbox value="video">video</a-checkbox>
            </a-checkbox-group>
          </div>

          <!-- 提交 -->
          <a-button type="primary" @click="onSubmitAdRepeat">提交</a-button>
        </a-space>
      </a-card>
      <a-card title="广告时间间隔循环展示项">
        <!-- 选项 infinity-->
        <a-space size="large" direction="vertical">
          <a-space size="large">
            循环展示项
            <a-checkbox-group
              v-model="adControl.infinity"
              style="display: flex; gap: 12px"
            >
              <a-checkbox value="banner">banner</a-checkbox>
              <a-checkbox value="interstitial">interstitial</a-checkbox>
              <a-checkbox value="video">video</a-checkbox>
            </a-checkbox-group>
          </a-space>

          <a-space size="large">
            延迟(ms)
            <a-input-number
              v-model="adControl.infinityDelay"
              :min="0"
            ></a-input-number>
          </a-space>

          <!-- 提交 -->
          <a-button type="primary" @click="onSubmitAdInfinity">提交</a-button>
        </a-space>
      </a-card>
      <a-card title="广告地区管理" v-if="false">
        <a-space size="large">
          地区名称添加
          <a-input v-model="areaAddName"></a-input>
          <a-button type="primary" @click="onAddArea">添加</a-button>
        </a-space>
        <div style="height: 20px"></div>
        <a-list>
          <template #header> 列表 </template>

          <a-list-item v-for="(item, index) of areaList">
            <a-space size="large">
              {{ item.name }}
              <a-tag bordered :color="item.active ? 'lime' : 'red'">
                {{ item.active ? "已启动" : "未启动" }}
              </a-tag>
            </a-space>
            <template #actions>
              <a-button
                type="primary"
                :status="item.active ? 'warning' : 'success'"
                @click="
                  () => {
                    item.active = !item.active;
                    postSaveCity();
                  }
                "
              >
                {{ item.active ? "禁用" : "启用" }}
              </a-button>
              <a-button
                type="primary"
                status="danger"
                @click="
                  () => {
                    areaList.splice(index, 1);
                    postSaveCity();
                  }
                "
              >
                删除
              </a-button>
            </template>
          </a-list-item>
        </a-list>
      </a-card>
    </a-space>
  </div>
</template>

<script setup>
import { ref, reactive, toRaw } from "vue";
import { axios, PathBuilder } from "@/api/index.js";
import { Message } from "@arco-design/web-vue";
const builder = new PathBuilder();

const initData = reactive({
  adShowCount: 0
});

const adShow = ref(false);

const areaAddName = ref("");

// 新增：广告初始展示项数组
const adControl = reactive({
  initial: [],
  infinityDelay: 1000,
  infinity: [],
  repeat: []
});

const areaList = ref([]);

const adminBuilder = new PathBuilder("/admin");

function onAdShow(e) {
  axios
    .get(builder.build("/admin/set-show"), {
      show: e
    })
    .then((resp) => {
      adShow.value = e;
    });
}

function onAddArea() {
  if (!areaAddName.value) {
    Message.error("地区名称不能为空");
    return;
  }
  areaList.value.push({
    id: Date.now(),
    name: areaAddName.value,
    active: true
  });
  postSaveCity();
}

function postSaveCity() {
  axios
    .post(adminBuilder.build("/save-city"), toRaw(areaList.value))
    .then((resp) => {
      Message.success("设置成功");
    })
    .catch(() => {
      Message.error("设置失败");
    })
    .finally(() => {
      getAdminData();
    });
}

// 设置初始值对象
function onSumbitInit() {
  const sdData = toRaw(initData);
  axios
    .post(builder.build("/init/set"), {
      data: sdData
    })
    .then((resp) => {
      Message.success("设置成功");
    });
}

// 新增：提交广告初始展示项
function onSubmitAdInitial() {
  const arr = adControl.initial || [];
  axios
    .post(adminBuilder.build("/ad-set"), {
      initial: arr
    })
    .then((resp) => {
      Message.success("设置成功");
    })
    .catch(() => {
      Message.error("设置失败");
    });
}

// 新增：提交广告重复展示项
function onSubmitAdRepeat() {
  const arr = adControl.repeat || [];
  axios
    .post(adminBuilder.build("/ad-set"), {
      repeat: arr
    })
    .then(() => {
      Message.success("设置成功");
    })
    .catch(() => {
      Message.error("设置失败");
    });
}

// 新增：提交广告时间间隔循环展示项（包含延迟）
function onSubmitAdInfinity() {
  const payload = {
    infinity: adControl.infinity || [],
    infinityDelay: adControl.infinityDelay || 0
  };
  axios
    .post(adminBuilder.build("/ad-set"), payload)
    .then(() => {
      Message.success("设置成功");
    })
    .catch(() => {
      Message.error("设置失败");
    });
}

(function () {
  axios.get(builder.build("/init")).then((resp) => {
    Object.assign(initData, resp.data);
    // console.log(resp);
  });

  {
    axios.get(adminBuilder.build("/ad-init")).then((resp) => {
      const { data } = resp;
      // console.log("ad-init->", data);
      if (data) {
        if (data.initial) {
          adControl.initial = String(data.initial)
            .split(",")
            .map((s) => s.trim())
            .filter(Boolean);
        } else if (Array.isArray(data)) {
          adControl.initial = data.initial;
        }

        // repeat 可能是数组或逗号字符串
        if (data.repeat) {
          adControl.repeat = Array.isArray(data.repeat)
            ? data.repeat
            : String(data.repeat)
                .split(",")
                .map((s) => s.trim())
                .filter(Boolean);
        }

        // infinity 及延迟
        if (data.infinity) {
          adControl.infinity = Array.isArray(data.infinity)
            ? data.infinity
            : String(data.infinity)
                .split(",")
                .map((s) => s.trim())
                .filter(Boolean);
        }
        if (typeof data.infinityDelay !== "undefined") {
          adControl.infinityDelay =
            Number(data.infinityDelay) || adControl.infinityDelay;
        }
      }
    });
  }
  getAdminData();
})();

// 包含是否打开广告 地区列表
function getAdminData() {
  axios.get(adminBuilder.build("/data")).then((resp) => {
    const { data } = resp;
    console.log("data->", data);
    areaList.value = data.filter;
    adShow.value = data.showAD;
  });
}
</script>

<style lang="less" scoped></style>
